﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TinyIM2013.Packets
{
    public class PReceive_0825:PReceive
    {
        public byte[] TokenData { get; set; }
        public PHeader PacketHead { get; set; }
        internal bool TryParse(byte[] packetData, out PReceive_0825 packet)
        {
            packet = new PReceive_0825();
            packet.PacketHead = PacketUtility.GetPHead(packetData);
            byte[] teaKey = IMKeyCollection.Instance.GetKey(packet.PacketHead.IMAccount, PCmd.CMD_0825);
            byte[] encryptedData = GetEnctyptedData(packetData);     
            byte[] decryptedData = TEAUtility.Decrypt(encryptedData, 0, encryptedData.Length, teaKey);
            if (decryptedData != null)
            {
                TokenData = GetTokenData(decryptedData);
                return true;
            }
            else
            {
                return false;
            }
        }

        private static byte[] GetTokenData(byte[] decryptedData)
        {
            byte[] returnBytes = new byte[] { };
            try
            {
                if (decryptedData[4].Equals(new byte[] { 0x38 }))
                {
                    Array.Copy(decryptedData, 5, returnBytes, 0, 56);
                    return returnBytes;
                }
            }
            catch
            {
                
            }
            return null;
        }

        internal byte[] GetEnctyptedData(byte[] packetData)
        {
            try
            {
                byte[] returnBytes = new byte[packetData.Length - 15];
                Array.Copy(packetData, 14, returnBytes, 0, packetData.Length - 15);
                return returnBytes;
            }
            catch { return null; }
        }

        public bool TryParse(byte[] packetData, out PReceive packet)
        {
            throw new NotImplementedException();
        }


        public byte[] GeneratePacket()
        {
            throw new NotImplementedException();
        }

        public void SendPacket()
        {
            throw new NotImplementedException();
        }
    }
}
